<!-- <template>
  <div>
    <h1>文件上传</h1>
    <input type="file" @change="handleFileChange" />
    <button @click="uploadFile" :disabled="!file">上传文件</button>
    <div v-if="progress > 0">
      上传进度: {{ progress }}%
    </div>
    <div v-if="message">{{ message }}</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      file: null, // 选择的文件
      fileName: '', // 文件名
      chunkSize: 1 * 1024 * 1024, // 每个文件块的大小（1MB）
      totalChunks: 0, // 文件总块数
      progress: 0, // 上传进度
      message: '', // 上传结果消息
      maxConcurrentUploads: 3, // 最大并发上传数
      uploadQueue: [], // 上传队列
    };
  },
  methods: {
    // 处理文件选择
    handleFileChange(event) {
      this.file = event.target.files[0];
      this.fileName = this.file.name;
      this.totalChunks = Math.ceil(this.file.size / this.chunkSize);
      this.uploadQueue = Array.from({ length: this.totalChunks }, (_, i) => i);
    },
    // 上传文件块
    async uploadChunk(chunkIndex) {
      const start = chunkIndex * this.chunkSize;
      const end = Math.min(start + this.chunkSize, this.file.size);
      const chunk = this.file.slice(start, end);

      const formData = new FormData();
      formData.append('file', chunk);
      formData.append('fileName', this.fileName);
      formData.append('currentChunk', chunkIndex);
      formData.append('totalChunks', this.totalChunks);

      try {
        await axios.post('http://127.0.0.1:8000/uploads/', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        this.updateProgress(chunkIndex);
        this.message = `上传中... ${this.progress}%`;
      } catch (error) {
        console.error(`上传块 ${chunkIndex} 失败:`, error);
        this.retryChunk(chunkIndex); // 重试失败的块
      }
    },
    // 更新进度
    updateProgress(chunkIndex) {
      this.progress = Math.round(((chunkIndex + 1) / this.totalChunks) * 100);
    },
    // 重试失败的块
    retryChunk(chunkIndex) {
      setTimeout(() => {
        this.uploadChunk(chunkIndex);
      }, 1000); // 1秒后重试
    },
    // 上传文件
    async uploadFile() {
      if (!this.file) {
        this.message = '请选择一个文件！';
        return;
      }

      this.message = '开始上传...';
      this.progress = 0;

      // 并发控制
      const concurrentUploads = [];
      while (this.uploadQueue.length > 0) {
        const chunkIndex = this.uploadQueue.shift();
        concurrentUploads.push(this.uploadChunk(chunkIndex));

        if (concurrentUploads.length >= this.maxConcurrentUploads) {
          await Promise.race(concurrentUploads);
          concurrentUploads.shift();
        }
      }

      await Promise.all(concurrentUploads);
      this.message = '上传成功！';
    },
  },
};
</script> -->


<template>
  <div>
  <div id="main" style="width:200px;height:300px;"></div>
  
   <el-row>
      <el-col :span="10"><div class="grid-content ep-bg-purple-dark" />
      <ul>
     
     {{data}}
      </ul>
      </el-col>
    
   </el-row>
  
    
    
  </div>
  </template>
  
<script setup>
// import {ref,onMounted}  from 'vue'

// //搜索用的
// const socket = ref(null)
// const data = ref()

// const initwesockt=()=>{
//     socket.value = new WebSocket("ws://localhost:8000/room/1/");

//     // 当客户端和服务端刚创建好连接(self.accept)之后，自动触发.
//     socket.value.onopen =  (event)=>{
//         console.log("连接成功")
//     }

//     // 回调函数，客户端接收服务端消息
//     socket.value.onmessage =  (event)=>{
    
//         data.value=event.data
//     }


// }

// onMounted(()=>{
//     initwesockt()
// })

import { ref, onMounted } from 'vue'
import axios from 'axios';

const socket = ref(null)
const data = ref()

const initwesockt = () => {
    socket.value = new WebSocket("ws://localhost:8000/ws/room/1/");

    socket.value.onopen = (event) => {
        console.log("连接成功");
        // 发送 HTTP 请求到 TestWebsocket 视图
        axios.get('http://127.0.0.1:8000/room/')
          .then(response => {
                console.log('HTTP 请求成功', response.data);
            })
          .catch(error => {
                console.error('HTTP 请求失败', error);
            });
    };

    socket.value.onmessage = (event) => {
        data.value = event.data;
    };

    socket.value.onerror = (event) => {
        console.error('WebSocket 连接出错:', event);
    };

    socket.value.onclose = (event) => {
        console.log('WebSocket 连接已关闭，关闭代码:', event.code);
    };
};


onMounted(() => {
    initwesockt()
})
</script>